package com.kit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jplus.core.utill.HttpClientUtil;

public class IPKit {

	public static void main(String[] args) {
		System.out.println(getIpBD("58.247.17.210"));
	}

	public static Data getIP(String ip) {
		String url = "http://ip-api.com/json/";
		HttpClientUtil http = new HttpClientUtil();
		String res = http.doGet(url + ip + "?lang=zh-CN");
		System.err.println(res);
		JSONObject obj = JSON.parseObject(res);
		if ("success".equals(obj.getString("status"))) {
			Data data = new Data(ip, get(obj, "country"), get(obj, "area"), get(obj, "region"), get(obj, "city"), "", get(obj, "isp"));
			return data;
		}
		return null;
	}

	public static Data getIpBD(String ip) {
		// https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=112.3.27.3&co=&resource_id=6006&t=1560236348352&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110201437439945442318_1560231859409&_=1560231859417
		String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?co=&resource_id=6006&t=1560236348352&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&query=";
		HttpClientUtil http = new HttpClientUtil();
		http.setCharSet("gbk");
		String res = http.doGet(url + ip);
		res = res.substring(res.indexOf("(") + 1, res.lastIndexOf(")"));
		JSONObject jobj = JSON.parseObject(res);
		if ("0".equals(jobj.getString("status"))) {
			JSONObject obj = jobj.getJSONArray("data").getJSONObject(0);
			String local[]=get(obj, "location").split(" ");
			Data data = new Data(ip, "", local[0], "", "", "", local[1]);
			return data;
		}
		return null;
	}
	public static Data getIpTB(String ip) {
		String url = "http://ip.taobao.com/service/getIpInfo.php?ip=";
		HttpClientUtil http = new HttpClientUtil();
		String res = http.doGet(url + ip);
		JSONObject jobj = JSON.parseObject(res);
		if (jobj.getInteger("code") == 0) {
			JSONObject obj = jobj.getJSONObject("data");
			Data data = new Data(ip, get(obj, "country"), get(obj, "area"), get(obj, "region"), get(obj, "city"), "", get(obj, "isp"));
			return data;
		}
		return null;
	}

	private static String get(JSONObject obj, String key) {
		return obj.getString(key);
	}

	public static class Data {
		String ip;
		String country;
		String area;
		String region;
		String city;
		String county;
		String isp;
		public Data(String ip, String country, String area, String region, String city, String county, String isp) {
			this.ip = ip;
			this.country = country;
			this.area = area;
			this.region = region;
			this.city = city;
			this.county = county;
			this.isp = isp;
		}

		public String getAddr() {
			return country + area + region + city + county;
		}

		@Override
		public String toString() {
			return ip + "," + getAddr() + "," + isp;
		}

	}

}
